function renderProducts(products) {
    const list = document.getElementById('productList');
    list.innerHTML = '';
    products.forEach(p => {
        list.innerHTML += `
            <div class="product-card">
                <img src="${p.image}" alt="${p.name}" onerror="this.src='images/icons/default.png'">
                <h3>${p.name}</h3>
                <p>￥${p.price}</p>
                <button onclick="location.href='pages/product.html?id=${p.id}'">查看详情</button>
                <button onclick="addToCart(${p.id})">加入购物车</button>
            </div>
        `;
    });
}
function loadAllProducts() {
    renderProducts(getProducts());
}
function filterCategory(cat) {
    if (cat === '全部') return loadAllProducts();
    const filtered = getProducts().filter(p => p.category === cat);
    renderProducts(filtered);
}
function addToCart(id) {
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    const idx = cart.findIndex(item => item.id == id);
    if (idx > -1) cart[idx].quantity += 1;
    else cart.push({id, quantity: 1});
    localStorage.setItem('cart', JSON.stringify(cart));
    alert('已加入购物车');
}
document.addEventListener('DOMContentLoaded', function() {
    loadAllProducts();
    document.getElementById('searchBtn').onclick = function() {
        const kw = document.getElementById('searchInput').value.trim();
        const filtered = getProducts().filter(p => p.name.includes(kw));
        renderProducts(filtered);
    };
    // 登录状态显示
    const user = localStorage.getItem('currentUser');
    if (user) {
        document.getElementById('welcomeUser').textContent = '欢迎，' + user;
        document.getElementById('loginLink').style.display = 'none';
        document.getElementById('profileLink').style.display = '';
        document.getElementById('logoutBtn').style.display = '';
        document.getElementById('logoutBtn').onclick = function() {
            localStorage.removeItem('currentUser');
            location.reload();
        };
    }
});
function showProductDetail() {
    const params = new URLSearchParams(location.search);
    const id = params.get('id');
    const p = getProductById(id);
    if (!p) return document.getElementById('productDetail').textContent = '商品不存在';
    document.getElementById('productDetail').innerHTML = `
        <img src="../${p.image}" alt="${p.name}" onerror="this.src='../images/icons/default.png'">
        <h3>${p.name}</h3>
        <p>${p.desc}</p>
        <p>￥${p.price}</p>
        <button onclick="addToCart(${p.id})">加入购物车</button>
    `;
}